package com.example.wryproject;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.FormBindingData;
import ohos.aafwk.ability.IAbilityConnection;
import ohos.aafwk.ability.ProviderFormInfo;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.window.service.WindowManager;
import ohos.bundle.ElementName;
import ohos.bundle.IBundleManager;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.rpc.IRemoteObject;
import ohos.security.SystemPermission;
import ohos.utils.zson.ZSONObject;

import com.example.wryproject.database.CardData;
import com.example.wryproject.service.MusicServiceAbility;
import com.example.wryproject.slice.MainAbilitySlice;
import com.example.wryproject.utils.DatabaseUtils;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 应用启动页
 */
public class MainAbility extends Ability {
    public static final int DEFAULT_DIMENSION_2X2 = 2;
    private static final int INVALID_CARD_ID = -1;
    private static final HiLogLabel TAG = new HiLogLabel(HiLog.DEBUG, 0x0, MainAbility.class.getName());
    private static final int PERMISSION_REQUEST_CODE = 0;
    private EventHandler eventHandler;
    private MusicServiceAbility.MusicRemoteObject musicRemoteObject;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setMainRoute(MainAbilitySlice.class.getName());
        getWindow().addFlags(WindowManager.LayoutConfig.MARK_TRANSLUCENT_STATUS);//沉浸式状态栏
        initJumpHandle();
        requestPermission();
    }

    @Override
    protected void onActive() {
        super.onActive();
    }

    // 向用户申请相关权限的授权
    private void requestPermission() {
        String[] permissions = {
            SystemPermission.READ_MEDIA,
            SystemPermission.WRITE_MEDIA,
            SystemPermission.READ_USER_STORAGE,
            SystemPermission.WRITE_USER_STORAGE,
            SystemPermission.KEEP_BACKGROUND_RUNNING
        };
        List<String> permissionList = Arrays.stream(permissions)
            .filter(permission -> verifySelfPermission(permission) != IBundleManager.PERMISSION_GRANTED)
            .collect(Collectors.toList());
        if (permissionList.isEmpty()) {
            startService();
            eventHandler.sendEvent(0, 1000);
            return;
        }
        // 向用户申请相关权限的授权
        requestPermissionsFromUser(permissionList.toArray(new String[permissionList.size()]),
            PERMISSION_REQUEST_CODE);
    }

    /**
     * 通过eventHandler延时跳转下一页面
     */
    private void initJumpHandle() {
        EventRunner eventRunner = EventRunner.getMainEventRunner();
        eventHandler = new EventHandler(eventRunner) {
            @Override
            protected void processEvent(InnerEvent event) {
                super.processEvent(event);
                startMusicAbility();
                terminateAbility();
            }
        };
    }

    @Override
    public void onRequestPermissionsFromUserResult(int requestCode, String[] permissions, int[] grantResults) {
        if (permissions == null || permissions.length == 0 || grantResults == null || grantResults.length == 0) {
            return;
        }
        for (int grantResult : grantResults) {
            //判断权限是否通过，如不通过则return结束代码段
            if (grantResult != IBundleManager.PERMISSION_GRANTED) {
                return;
            }
        }
        startService();
        //权限通过后发送跳转事件
        eventHandler.sendEvent(0, 1000);
    }

    /**
     * 启动并连接服务
     */
    public void startService() {
        IAbilityConnection connection = new IAbilityConnection() {
            @Override
            public void onAbilityConnectDone(ElementName elementName, IRemoteObject remoteObject, int i) {
                if (remoteObject instanceof MusicServiceAbility.MusicRemoteObject) {
                    musicRemoteObject = (MusicServiceAbility.MusicRemoteObject) remoteObject;
                }
            }

            @Override
            public void onAbilityDisconnectDone(ElementName elementName, int i) {
            }
        };
        Intent startService = new Intent();
        Operation operation = new Intent.OperationBuilder()
            .withDeviceId("")
            .withBundleName(getBundleName())
            .withAbilityName(MusicServiceAbility.class.getName())
            .build();
        startService.setOperation(operation);
        startAbility(startService);
        connectAbility(startService, connection);
    }

    /**
     * 启动播放页面
     */
    private void startMusicAbility() {
        Intent musicAbility = new Intent();
        Operation operation = new Intent.OperationBuilder()
            .withDeviceId("")
            .withBundleName(getBundleName())
            .withAbilityName(MusicAbility.class.getName())
            .build();
        musicAbility.setOperation(operation);
        startAbility(musicAbility);
    }

    @Override
    public void onStop() {
        super.onStop();
        eventHandler.removeAllEvent();
    }

    @Override
    protected ProviderFormInfo onCreateForm(Intent intent) {
        if (intent == null) {
            return new ProviderFormInfo();
        }
        //返回主界面后musicRemoteObject就会为空，此时操作卡片就需要重新获取musicRemoteObject对象
        musicRemoteObject = MusicServiceAbility.get();
        if (musicRemoteObject == null) {
            startService();
        }
        while (musicRemoteObject == null) {
        }
//        // 获取卡片id
        long cardId = INVALID_CARD_ID;
        if (intent.hasParameter(AbilitySlice.PARAM_FORM_IDENTITY_KEY)) {
            cardId = intent.getLongParam(AbilitySlice.PARAM_FORM_IDENTITY_KEY, INVALID_CARD_ID);
        }
        ProviderFormInfo providerFormInfo = new ProviderFormInfo();

        // 获取卡片规格
        int dimension = DEFAULT_DIMENSION_2X2;
        if (intent.hasParameter(AbilitySlice.PARAM_FORM_DIMENSION_KEY)) {
            dimension = intent.getIntParam(AbilitySlice.PARAM_FORM_DIMENSION_KEY, DEFAULT_DIMENSION_2X2);
        }
        CardData cardData = new CardData(cardId, dimension);
        DatabaseUtils.insertCardData(cardData, DatabaseUtils.getOrmContext(this));
        musicRemoteObject.updateCardCover();
        musicRemoteObject.lrcLoading("暂无歌词数据");
        providerFormInfo.setJsBindingData(new FormBindingData());
        return providerFormInfo;
    }

    @Override
    protected void onUpdateForm(long formId) {
        super.onUpdateForm(formId);
        HiLog.info(TAG, "onUpdateForm");
    }

    @Override
    protected void onDeleteForm(long formId) {
        HiLog.info(TAG, "onDeleteForm: formId=" + formId);
        super.onDeleteForm(formId);
        DatabaseUtils.deleteCardData(formId, DatabaseUtils.getOrmContext(this));
    }

    @Override
    protected void onTriggerFormEvent(long formId, String message) {
        super.onTriggerFormEvent(formId, message);

        //返回主界面后musicRemoteObject就会为空，此时操作卡片就需要重新获取musicRemoteObject对象
        musicRemoteObject = MusicServiceAbility.get();
        if (musicRemoteObject == null) {
            startService();
        }
        while (musicRemoteObject == null) {
        }

        String musicMessage = (String) ZSONObject.stringToZSON(message).get("message");
        switch (musicMessage) {
            case "last":
                musicRemoteObject.lastMusic();
                break;
            case "play":
                //当用户杀死应用时，player就会为null，此时点击卡片播放，需做判空处理
                if (musicRemoteObject.getPlayer() == null) {
                    musicRemoteObject.initPlayer(this);
                }
                musicRemoteObject.playMusic();
                musicRemoteObject.updateCardCover();
                break;
            case "next":
                musicRemoteObject.nextMusic();
                break;
        }
    }
}
